layui.use(['element', 'form', 'table', 'laytpl', 'jquery', 'util', 'request', 'layer'], function () {
    let element = layui.element,
        $ = layui.jquery,
        form = layui.form,
        table = layui.table,
        laytpl = layui.laytpl,
        $request = layui.request,
        layer = layui.layer,
        util = layui.util;

    //登录面板弹框索引
    let loginDbPanel;
    //生成面板弹窗索引
    let generatePanel;
    //当前选择的连接名
    let connectionName;
    //  已经连接上连接的集合
    let linkedConnectionArray = [];
    //点击生成时，给后端的数据
    let generateData = {};


    //数据库类型
    let dbType = "Mysql8";
    //url链接前缀
    let pre = "jdbc:mysql://";
    //url 数据库地址部分
    let host = "localhost";
    //url 端口部分
    let port = "3306";
    //url 数据库名部分
    let dbName = "";
    //设置mysql8的时区设置
    let timezone = "ServerTimezone=GMT%2b8"

    //渲染左边列
    renderLinked();


    //渲染模块下拉列表
    renderModuleSelect();

    //头部事件
    util.event('lay-header-event', {
        menuRight: function () {
            loginDbPanel = layer.open({
                type: 1
                , content: $("#database")
                , offset: 'center' //右上角
                , anim: 5
                , shadeClose: true
                , cancel: function () {
                    cleanLoginForm()
                }
            });
        }
    });
    //url和数据库各个信息的对应关系
    util.event('lay-blur', {
        host: function () {
            host = $("#host").val();
            if (dbType === "Oracle") {
                host = "@" + host;
            }

            urlUpdate();
        }
        , port: function () {
            port = $("#port").val();
            urlUpdate();
        }
        , database: function () {
            dbName = $("#dbName").val();
            urlUpdate();
        }
        , url: function () {
            let url = $("#url").val();
            if (dbType === "Oracle") {
                //截取host
                let localhostReg = /(?<=@).+(?=:)/;
                let localhostResult = url.match(localhostReg);
                if (localhostResult != null && localhostResult.length > 0) {
                    host = localhostResult[0];
                } else {
                    host = "";
                }
            } else {
                //截取host
                let localhostReg = /(?<=:\/\/).+(?=:)/;
                let localhostResult = url.match(localhostReg);
                if (localhostResult != null && localhostResult.length > 0) {
                    host = localhostResult[0];
                } else {
                    host = "";
                }
            }
            //截取port
            let portReg = /(?<=:).+(?=\/)/;
            let portResult = url.match(portReg);
            if (portResult != null && portResult.length > 0) {
                port = portResult[0];
                if (port.lastIndexOf(":") > -1) {
                    port = port.substr(port.lastIndexOf(":") + 1)
                }
            } else {
                port = "";
            }
            //截取数据库名
            let i = url.indexOf("?");
            if (i > -1) {
                dbName = url.substring(url.lastIndexOf("/") + 1, i);
            } else {
                dbName = url.substr(url.lastIndexOf("/") + 1);
            }
            update();
        }
    }, 'input')
    $("#linked").on("click", "li", function () {
        let connectionName = this.getElementsByTagName("a")[0].innerText;
        renderTableInfo(connectionName);
    })
    //测试链接
    form.on('submit(test)', function (data) {
        data.field.test = true;
        $request.post("/viewer/connect", data.field,)
        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    });
    //链接跳转
    form.on('submit(connect)', function (data) {
        data.field.test = false;

        $request.post("/viewer/connect", data.field, function () {
            layer.close(loginDbPanel);
            renderLinked();
            connectionName = data.field.name;
            renderTableInfo(connectionName)
        })

        cleanLoginForm()
        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    });
    $("#generate").click(function () {
        var checkStatus = table.checkStatus('table'); //idTest 即为基础参数 id 对应的值
        if (checkStatus.data.length === 0) {
            layer.msg("请选择要生成的表");
            return
        }
        //选出表名组成数组
        let tableNames = checkStatus.data.map((item) => {
            return item.tableJdbcName;
        })
        //构建传输给后台的数据对象
        generateData = {
            connectionName: connectionName,
            tableNames: tableNames
        }

        generatePanel = layer.open({
            type: 1
            , content: $("#generateForm")
            , offset: 'center' //右上角
            , anim: 5
            , shadeClose: true
            , cancel: function () {
                cleanGenerateForm()
            }
        });

    })
    //设置是否需要显示数据库配置信息
    form.on('select(flag)', function (data) {
        if (data.value === "2") {
            $("#edit").removeAttr("hidden");
            addVerify();
            urlUpdate();
            update();
        }
        if (data.value === "1") {
            $("#edit").attr("hidden", "hidden");
            removeVerify();
        }
    });
    //数据库类型的变化
    form.on('select(type)', function (data) {
        let val = data.value;
        switch (val) {
            case "MySql8":
                pre = "jdbc:mysql://";
                dbType = "Mysql8";
                host = "localhost"
                dbName = "";
                port = "3306"
                break;
            case "MySql5":
                pre = "jdbc:mysql://";
                port = "3306"
                host = "localhost"
                dbType = "Mysql5";
                dbName = "";
                break;
            case "DM":
                pre = "jdbc:dm://";
                host = "localhost"
                //达梦数据库的默认数据库名为DAMENG
                dbName = "DAMENG"
                //达梦数据库默认端口为 5236
                port = "5236";
                dbType = "DM";
                break;
            case "Oracle":
                pre = "jdbc:oracle:thin:";
                host = "localhost"
                //达梦数据库的默认数据库名为DAMENG
                dbName = "orcl"
                //达梦数据库默认端口为 5236
                port = "1521";
                dbType = "Oracle";
                break;
        }
        update();
        urlUpdate();
    });
    //生成到其他模块复选框事件
    form.on('radio(generateOther)', function (data) {
        if (data.value === '2') {
            $("#moduleSelect").attr("hidden", "hidden");
        } else {
            $("#moduleSelect").removeAttr("hidden");
        }
    });
    //取消生成文件
    form.on('submit(cancel)', function (data) {
        //关闭弹窗
        layer.close(generatePanel);
        //重新渲染表单
        cleanGenerateForm()
        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    });
    //生成文件
    form.on('submit(sure)', function (data) {
        generateData.moduleName = data.field.moduleName;
        $request.post("/viewer/generate", generateData, () => {
        })

        //关闭弹窗
        layer.close(generatePanel);
        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    });


    //更新host port  name(数据库名字)
    function update() {
        $("#host").val(host);
        $("#port").val(port);
        $("#dbName").val(dbName);
    }

    //更新url
    function urlUpdate() {
        let a = pre + (dbType === "Oracle" ? "@" + host : host) + (port === "" ? "" : ":" + port + "/") + dbName + (dbType === "Mysql8" ? "?" + timezone : "");
        $("#url").val(a);
    }


    //增加隐藏input的校验
    function addVerify() {
        $("#host").attr("lay-verify", "required");
        $("#port").attr("lay-verify", "required");
        $("#url").attr("lay-verify", "required");
        $("#dbName").attr("lay-verify", "required");
        $("#username").attr("lay-verify", "required");
        $("#password").attr("lay-verify", "required");
    }

    //删除隐藏input的校验
    function removeVerify() {
        $("#host").removeAttr("lay-verify");
        $("#dbName").removeAttr("lay-verify");
        $("#port").removeAttr("lay-verify");
        $("#url").removeAttr("lay-verify");
        $("#username").removeAttr("lay-verify");
        $("#password").removeAttr("lay-verify");
    }

    //渲染已连接的数据库
    function renderLinked() {
        $request.get("/viewer/linkedDBs?t=" + new Date().getDate(), function (data) {
            linkedConnectionArray = data;

            let getTpl = linkedArray.innerHTML
                , linked = document.getElementById('linked');
            laytpl(getTpl).render(data, function (html) {
                linked.innerHTML = html;
            });

            //渲染表格
            renderTableInfo();
        })
    }

    //数据表格
    function renderTableInfo(connectName) {
        if (connectName == null && linkedConnectionArray.length !== 0) {
            connectName = linkedConnectionArray[0].name
            connectionName = connectName;
        }

        if (linkedConnectionArray.length === 0) {
            return
        }

        //去除生成按钮的禁用
        let $generate = $("#generate");
        $generate.removeClass("layui-btn-disabled")
        $generate.removeAttr("disabled")

        //渲染表格
        table.render({
            elem: '#demo'
            , id: "table"
            , url: "/viewer/tablesInfo" //数据接口
            , method: "post"
            , contentType: 'application/json'
            , where: {
                connectionName: connectName
            }
            , request: {
                pageName: 'page' //页码的参数名称，默认：page
                , limitName: 'pageSize' //每页数据量的参数名，默认：limit
            }
            , page: true //开启分页
            , limits: [30, 50, 70]
            , parseData: function (res) { //res 即为原始返回的数据
                if (res.code !== 20000) {
                    return {
                        "code": 200, //解析接口状态
                        "msg": "error: " + res.msg, //解析提示文本
                    };
                } else {
                    return {
                        "code": 0, //解析接口状态
                        "msg": res.msg, //解析提示文本
                        "count": res.data.total, //解析数据长度
                        "data": res.data.data, //解析数据列表
                        "page": res.data.page,
                        "limit": res.data.pageSize,

                    };
                }

            }
            , cols: [[ //表头
                {type: 'checkbox', align: "center", width: 80,}
                , {type: 'numbers', title: '序号', align: "center", width: 80,}
                , {field: 'tableJdbcName', title: '表名', align: "center"}
                , {field: 'comment', title: '表注释', align: "center"}
            ]]
        });
    }

    function cleanLoginForm() {
        //数据库类型
        dbType = "Mysql8";
        //url链接前缀
        pre = "jdbc:mysql://";
        //url 数据库地址部分
        host = "localhost";
        //url 端口部分
        port = "3306";
        //url 数据库名部分
        dbName = "";
        //设置mysql8的时区设置
        timezone = "ServerTimezone=GMT%2b8"
        //数据库类型默认设置为Mysql8
        $("#dbType").val("MySql8")
        $("#flag").val("1")
        //连接名称设置为空
        $("#name").val("")
        $("#host").val("")
        $("#port").val("")
        $("#dbName").val("")
        $("#url").val("")
        $("#username").val("")
        $("#password").val("")
        form.render(null, 'database');

        //隐藏元素
        $("#edit").attr("hidden", "hidden");
    }

    //清除生成文件面板的数据
    function cleanGenerateForm() {
        $("#moduleSelect").attr("hidden", "hidden");

        //重新渲染表单
        $("#yes").removeAttr("checked");
        $("#no").prop("checked", true);

        layui.form.render('radio');
    }

    function renderModuleSelect() {
        //发送请求获取模块名
        $request.get("/viewer/modules", function (data) {
            console.log(data);
            let _moduleName = document.querySelector("#moduleName");
            data.forEach((item, index) => {
                _moduleName.add(new Option(item, item));
            })
            form.render('select');
        })
    }
});